package org.dant.ant.extension.tasks;

import java.io.*;
import java.util.*;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.dant.ant.extension.tasks.commands.JavaCommand;
import org.dant.ant.extension.tasks.internal.Endpoint;
import org.dant.ant.extension.tasks.internal.RemoteCommand;

public class RemoteJava extends RemoteExecutable {
    protected CommandlineJava jcmdl = new CommandlineJava();

    public RemoteJava() {
        rcmd = new JavaCommand();
    }

    public void setClasspath(Path s) {
        createClasspath().append(s);
    }
    
    public Path createClasspath() {
        return jcmdl.createClasspath(project).createPath();
    }
  
    public void setClasspathRef(Reference r) {
        createClasspath().setRefid(r);
    }
  
    public void setJar(File jarfile) throws BuildException {
        if (jcmdl.getClassname() != null) {
            throw new BuildException("Cannot use 'jar' and 'classname' "
                                     + "attributes in same command.");
        }
        jcmdl.setJar(jarfile.getAbsolutePath());
    }

    public void setClassname(String s) throws BuildException {
        if (jcmdl.getJar() != null) {
            throw new BuildException("Cannot use 'jar' and 'classname' "
                                     + "attributes in same command");
        }
        jcmdl.setClassname(s);
    }


    public Commandline.Argument createArg() {
        return jcmdl.createArgument();
    }

    public Commandline.Argument createJvmarg() {
        return jcmdl.createVmArgument();
    }

    public String getClassname() {
        return jcmdl.getClassname();
    }

    public String[] getJavaCommandLine() {
        return jcmdl.getCommandline();
    }

    public void resolveDir() throws IOException {
        for (Iterator iter = destHosts.keySet().iterator(); iter.hasNext();) {
            Endpoint ep = (Endpoint) iter.next();
            RemoteCommand request = (RemoteCommand)destHosts.get(ep);
            File basedir = ep.getBaseDir();

            File execdir = (dirstring == null) ? null : new File(dirstring);
            if (basedir == null || (execdir != null && execdir.isAbsolute())) {
                continue;
            }
            File absolutePath = fu.resolveFile(basedir, dirstring);
            request.appendParameters("dir", absolutePath);
        }
    }
}
